package com.dyh.quickdemo.bizDemo.syncWarehouseToWms;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/*
@Author=Joey Wheeler
@Date=2020/12/29 17:43
*/
@Slf4j
public class Macro {
    @AllArgsConstructor
    public class ActionWrap{
        public String desc;
        public Action action;
        public Macro fallback;
    }
    List<ActionWrap> actionWraps = new ArrayList<>();
    String desc;
    public Macro fallback;

    public static Macro init(String desc){
        Macro macro = new Macro();
        macro.desc = desc;
        return macro;
    }

    public Macro then(String desc,Action action,Macro macro){
        actionWraps.add(new ActionWrap(desc,action,macro));
        return this;
    }

    public Macro then(String desc,Action action){
        actionWraps.add(new ActionWrap(desc,action,null));
        return this;
    }

    public Macro then(Action action){
        actionWraps.add(new ActionWrap("",action,null));
        return this;
    }

    public void run(){
        for (int i = 0;i<actionWraps.size();i++){
            ActionWrap actionWrap = actionWraps.get(i);
            try {
                actionWrap.action.act();
                log.info("【宏-{}】  执行步骤{} 成功",desc,actionWrap.desc);
            } catch (Exception e) {
                log.error("【宏-{}】 执行步骤{} 出现异常e=",desc,actionWrap.desc,e);
                Macro anFallback = actionWrap.fallback;
                if (anFallback!=null)
                    actionWrap.fallback.run();
                 break;
//                Macro macro = actionWrap.fallback;
//                if (macro!=null){
//                    //log.error("宏{} 执行步骤{} 转入",desc,actionWrap.desc);
//                    //macro.run();
//                    break;
//                }
//                else
//                    break;
            }
        }

    }
}
